package com.fengxing.ams.pub.ip;

import java.text.MessageFormat;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fengxing.ams.pub.util.HttpClientUtils;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class TaobaoIPService implements IPService{
	private static Logger logger = LoggerFactory.getLogger(TaobaoIPService.class);
	private static final String TAOBAO_TEMPLATE = "http://ip.taobao.com/service/getIpInfo.php?ip={0}";
	
	@Override
	public String getAddress(String ip) {
		String output = httpRequest(ip);
		if(StringUtils.isNotBlank(output)) {
			return parse(output);
		}
		return null;
	}
	
	private String parse(String json) {
		JsonObject jsonObject = null;
		try {
			JsonParser jp = new JsonParser();
			jsonObject = jp.parse(json).getAsJsonObject().getAsJsonObject("data");
			JsonElement cityJsonObj = jsonObject.get("city");
			String city = cityJsonObj.getAsString();
			return city;
		} catch (Exception e) {
		}
		return null;
	}
	
	
	private String httpRequest(String ip) {
		if(StringUtils.isBlank(ip)) {
			return null;
		}
		String inputUrl = buildRequest(ip);
		String output = HttpClientUtils.get(inputUrl, true);
		if (logger.isDebugEnabled()) {
			logger.debug("Input is : " + inputUrl);
			logger.debug("Output is : " + output);
		}
		return output;
	}
	
	private String buildRequest(String ip) {
		String url = MessageFormat.format(TAOBAO_TEMPLATE, ip);
		return url;
	}
}
